﻿using Simple.Framework;
using Simple.Framework.Ioc;
using Simple.Framework.Load;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

/*********************************************************
 * 命名空间 Simple.PrettyNet.Handle
 * 接口名称 SocketClassLoadProcess
 * 开发人员：zdm
 * 创建时间：2023/11/21 9:55:43
 * 描述说明：
 * 更改历史：
 * 
 * *******************************************************/
namespace SimpleNet.Handle
{
	public class SocketClassLoadProcess:BaseLoadProcess,IClassLoadProcess
	{
	
		private Type baseType;
		private List<HandleLabel> handleLabels;
		private SystemConfiguration sysCfg;

		private Type baseStringType;
		public SocketClassLoadProcess()
		{
			baseType = typeof(BaseHandle);
			baseStringType = typeof(BaseStringHandle);
			handleLabels=new List<HandleLabel>();

		}
		public override void Initializer()
		{
			base.container.Register<HandleLabel>();
			sysCfg=base.container.GetService<SystemConfiguration>();
			base.Initializer();
		}
		public override bool Process(Type type)
		{
			bool result = type.IsAssignableTo(baseType);
			if (result)
			{
				if (type.IsDefined(typeof(NumberRangeAttribute), true))
				{

					NumberRangeAttribute range = type.GetCustomAttribute<NumberRangeAttribute>();
					var handleLabel = container.GetService<HandleLabel>();
					handleLabel.MaxNumber = range.MaxMessageNumber;
					handleLabel.MinNumber = range.MinMessageNumber;
					handleLabel.HandType = type;
					if (handleLabels.Where(labels => labels.IsRange(range.MinMessageNumber) || labels.IsRange(range.MaxMessageNumber)).Any())
						throw new Exception("处理类的范围冲突,请检查,确保范围不重叠!");
					handleLabels.Add(handleLabel);
				}
			}
			if (type.IsAssignableTo(baseStringType)&&type.FullName!=baseStringType.FullName)
			{
				result = type.IsAssignableTo(baseStringType);
				sysCfg.StringMessageType = type;
			}
			return result;
		}

		public override void ProcessEnd()
		{
			container.RegistSingletonInstance(handleLabels);
			base.ProcessEnd();
		}
	}
}
